package com.kly.user.serviceImpl;

import com.alibaba.fastjson.JSONObject;
import com.fqgj.common.api.Response;
import com.fqgj.log.factory.LogFactory;
import com.fqgj.log.interfaces.Log;
import com.google.common.eventbus.AsyncEventBus;
import com.kly.user.db.dao.UserBehaviorLogDao;
import com.kly.user.db.entity.UserBehaviorLogEntity;
import com.kly.user.dto.UserBehaviorReq;
import com.kly.user.enums.AppEnum;
import com.kly.user.enums.LogActionEnum;
import com.kly.user.eventbus.ActionEnum;
import com.kly.user.eventbus.Event;
import com.kly.user.service.BehaviorService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;


/**
 * 用户操作行为表
 *
 * @author linqu
 */
@Service("behaviorService")
public class BehaviorServiceImpl implements BehaviorService {

    private static Log logger = LogFactory.getLog(BehaviorServiceImpl.class);
    @Resource
    UserBehaviorLogDao userBehaviorLogDao;
    @Resource
    AsyncEventBus asyncEventBus;


    /**
     * 用户行为记录
     *
     * @param userBehaviorReq 用户操作参数
     *                        actionType: 操作类型：1-首页照浏览
     *                        resultType: 操作结果：1-pass
     * @return
     */
    @Override
    public Response doAction(UserBehaviorReq userBehaviorReq) {
        if (Objects.isNull(userBehaviorReq) || StringUtils.isEmpty(userBehaviorReq.getUserCode())) {
            return Response.error("Params validate failed，userCode should not be empty");
        }
        if (Objects.isNull(userBehaviorReq.getActionType())) {
            return Response.error("Params validate failed，actionType should not be empty");
        }

        UserBehaviorLogEntity userBehaviorLogEntity = new UserBehaviorLogEntity();
        BeanUtils.copyProperties(userBehaviorReq, userBehaviorLogEntity);
        userBehaviorLogDao.insert(userBehaviorLogEntity);

        return Response.ok();
    }

    @Override
    public Response doLog(String userCode, String toUserCode, LogActionEnum logActionEnum, AppEnum appEnum) {

        try {
            asyncEventBus.post(buildEvent(userCode, toUserCode, logActionEnum, appEnum));
        } catch (Exception e) {
            logger.error("doLogFailed, userCode:{}, toUserCode:{}, logType:{}", userCode, toUserCode, logActionEnum.getValue(), e);
        }

        return Response.ok();
    }

    private Event buildEvent(String userCode, String toUserCode, LogActionEnum logActionEnum, AppEnum appEnum) {

        JSONObject contentJson = new JSONObject();
        contentJson.put("actionType", logActionEnum.getType());
        contentJson.put("actionName", logActionEnum.getValue());

        return Event.builder().eventActionEnum(ActionEnum.LOG).fromUserCode(userCode).toUserCode(toUserCode).app(appEnum)
                .content(contentJson.toJSONString()).build();
    }


    /**
     * 查询是否首次操作
     * @param userCode  用户码
     * @param actionType    操作类型
     * @return  false不是第一次操作，ture是第一次操作
     */
    @Override
    public Response<Boolean> isFirstTimeOperation(String userCode, Integer actionType){
        Map<String,Object> map=new HashMap<>();
        map.put("userCode",userCode);
        map.put("actionType",actionType);
        List<UserBehaviorLogEntity> userBehaviorLogEntities = userBehaviorLogDao.selectByParams(map);
        if (userBehaviorLogEntities!=null&&!userBehaviorLogEntities.isEmpty()){
            return Response.ok(false);
        }else {
            return Response.ok(true);
        }
    };
}
